﻿/**
 * SDrag.js
 * Simple Drag;
 */
$.SDrag = $({
	__init: function (e, hand, sets) {
		this.e = $E(e);
		this.hand = hand ? $E(hand) : this.e;
		var defaultSets = {
			axis: 'ALL'	,	//ALL, V, H
			cursor: 'move',
			maxZIndex: 1000
		};	
		this.sets = $.extend(defaultSets, sets || {});
		this.hand.css({cursor: this.sets.cursor});
		if (this.e.css('position') != 'absolute') {
			var pos =this.e.$('$$position');
			this.e.css('position:absolute;left:' + pos[0] + 'px;top:' + pos[1] + 'px');	
		}
		e = this.e, hand = this.hand, sets = this.sets;
		var axis = this.sets.axis.toUpperCase(), startCursorPointer, startPointer, oriZIndex;
		var start = function (evt) {
			startCursorPointer = [$(evt, 'x'), $(evt, 'y')];
			startPointer = [parseInt(e.css('left')) || 0, parseInt(e.css('top')) || 0];
			oriZIndex = e.css('z-index') || 0;
			e.css('z-index:' + sets.maxZIndex);
			if (document.body.setCapture){
          				document.body.setCapture();
       			} else if (window.captureEvents){
          				window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
       			}
			$.observe(document, 'mousemove', move);
			$.observe(document, 'mouseup', stop);
			(sets.onStartDrag || $.empty)(e);
			$(evt, 'stop');
		};
		var stop = function (evt) {
			e.css('z-index:' + oriZIndex);
			if (document.body.releaseCapture) {
              				document.body.releaseCapture();
            			} else if (window.captureEvents) {
              				window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
            			}
			$.stopObserving(document,'mousemove', move);
			$.stopObserving(document, 'mouseup', stop);
			(sets.onEndDrag || $.empty)(e);
			$(evt, 'stop');	
		};
		var move = function (evt) {
			var cp = [$(evt, 'x'), $(evt, 'y')], scp = startCursorPointer, sp = startPointer;
			var delta = [cp[0] - scp[0], cp[1] - scp[1]];
			var p = {}, p1 = {};
			if (axis == 'ALL' || axis == 'H') {
				var left = sp[0] + delta[0];
				if (sets.rangeX) {
					var rangeX = sets.rangeX;
					left = left < rangeX[0] ? rangeX[0] :  (left > rangeX[1] ? rangeX[1] : left);	
				}
				p1['left'] = left;
				p['left'] = left  + 'px';
			}
			if (axis == 'ALL' || axis == 'V') {
				var top = sp[1] + delta[1];
				if (sets.rangeY) {
					var rangeY = sets.rangeY;
					top = top < rangeY[0] ? rangeY[0] : (top > rangeX[1] ? rangeX[1] : top);	
				}
				p1['top'] = top;
				p['top'] = top + 'px';
			}
			if (sets.onDrag) sets.onDrag(p1);
			e.css(p);
			$(evt, 'stop');
		};
		var activated = false;
		this.activate = function () {
			if (activated) return;
			activated = true;
			hand.mousedown(start);
		};
		this.disable = function () {
			if (!activated) return;
			activated = false;
			hand.$mousedown(start);
		};
		this.activate();
	}
});